package com.ly.mpayment.rest.up.yezhikeji;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.HttpClient;
import com.ly.mpayment.core.util.StringUtils;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import com.ly.mpayment.rest.up.util.Util;
import org.apache.log4j.Logger;
import org.mortbay.util.MultiMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("yezhikeji")
public class YezhikejiRest {

    Logger logger = Logger.getLogger(YezhikejiRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;

    @SuppressWarnings("static-access")
    @Path("callBack")
    @POST
    public String callBack(String data) {
        logger.info("yezhikeji_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            MultiMap multiMap = Util.parceString(data);
            //支付结果 1 成功 2失败
            UpOrder order = upOrderService.findById(multiMap.getString("order_sn"));
            if (order != null && multiMap.getString("state").equals("SUCCESS") && order.getStatus() == Config.status[0]) {
                order.setRemark(multiMap.containsKey("official_sn") ? multiMap.getString("official_sn") : multiMap.getString("message"));
                RechargeRest.successUpOrder.add(order);
                return "SUCCESS";
            } else if (order != null && order.getStatus() == Config.status[0] && multiMap.getString("state").equals("CANCEL")) {
                order.setRemark(multiMap.getString("message"));
                RechargeRest.failtUpOrder.add(order);

                return "SUCCESS";
            } else {
                logger.info("yezhikeji_not_found_order:" + multiMap);
            }
        }
        return "fali";
    }


    /**
     * 订单提交
     *
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        JSONObject data = new JSONObject();
        data.put("act","refill");
        data.put("op","add");
        data.put("mchid",shop.getAppId());
        data.put("cardno",order.getUpphonenum());
        data.put("amount",order.getUpShopPro().getUpfacevalue());
        data.put("order_sn",order.getUporderuuid());
        data.put("notifyurl", URLEncoder.encode(shop.getOrderCallAddress()));
        data.put("sign",MD5.md5(StringSort.doSign(data)+"&key="+shop.getUpkey()));

        String result = HttpClient.postUrlFrom(shop.getOrderCommitAddress(),StringSort.jsonToString(data));
        logger.info("yezhikeji_result:"+result+","+order.getUpphonenum()+",:"+data.toString());
        try {
//            code	number	是	0成功 其它失败
//            msg	string	是	提示信息
//            data	json	否	额外信息 见下表
            JSONObject res = JSONObject.parseObject(result);
            //提交成功
            if( res.containsKey("code") && res.getString("code").equals("200")) {
                upOrderService.updateUpOrderMsg(order, res.getString("code"), res.containsKey("message") ? res.getString("message") : res.getString("code"));
            }else if(res.containsKey("code") && errorCode.contains(res.getString("code"))) {
                order.setRemark( res.getString("message"));
                RechargeRest.failtUpOrder.add(order);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(e.getMessage());
            upOrderService.addOrderMsg(order,"提单异常需要人工");
        }
    }

//     201，数据验证错误，具体信息查看message
//     202，找不到充值通道/查询接口为无此订单
//     203，余额不足
//     204，充值失败
//     205，上传的订单号重复
//     206，平台不支持该卡充值
//     207，充值库存已用完
//     0，信息验证错误，具体信息查看message
//     10021，签名验证失败或没有检测到签名数据
    Set<String> errorCode =  new HashSet(){{
        add("201");
        add("202");
        add("203");
        add("204");
        add("205");
        add("206");
        add("207");
        add("0");
        add("10021");
    }};


    /**
     * 订单查询
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {

        JSONObject data = new JSONObject();
        data.put("act","refill");
        data.put("op","query");
        data.put("mchid",shopInfo.getAppId());
        data.put("order_sn",upOrder.getUporderuuid());
        data.put("sign",MD5.md5(StringSort.doSign(data)+"&key="+shopInfo.getUpkey()));

        String result = HttpClient.postUrlFrom(shopInfo.getOrderStatusAddress(),StringSort.jsonToString(data));
        logger.info("yezhikejiqueryOrder:"+upOrder.getUpphonenum()+":"+result+","+StringSort.jsonToString(data));
        if (!StringUtils.isBlank(result)) {
            JSONObject jsonD = JSONObject.parseObject(result);
            if(jsonD.containsKey("code") && jsonD.getString("code").equals("200")){
                UpOrder order = upOrderService.findById(jsonD.getJSONObject("datas").getString("order_sn"));
                // status number	支付结果 0无效(订单创建失败时) 1等待支付 2支付成功 3支付失败
                if (order != null && jsonD.getJSONObject("datas").getString("order_state").equals("40") && order.getStatus() == Config.status[0]) {
                    order.setRemark(jsonD.containsKey("message") ? jsonD.getString("message") : jsonD.getJSONObject("datas").getString("order_state"));
                    RechargeRest.successUpOrder.add(order);
                } else if (order != null && order.getStatus() == Config.status[0]
                        && (jsonD.getJSONObject("datas").getString("order_state").equals("0"))) {
                    order.setRemark(jsonD.getString("message"));
                    RechargeRest.failtUpOrder.add(order);
                } else {
                    logger.info("yezhikeji_not_found_order:" + jsonD.getJSONObject("datas").getString("order_sn") + "," + upOrder.getUpphonenum());
                }
            } else{
                logger.info("yezhikeji_not_found_order:" + result+ "," + upOrder.getUpphonenum());
            }
        }
    }

}
